package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.MarketAd;
import com.cskaoyan.bean.MarketAdExample;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.mapper.MarketAdMapper;
import com.cskaoyan.service.admin.MarketAdService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author RXC
 * @date 2022/6/26 16:21
 */
@Service
@Transactional
public class MarketAdServiceImpl implements MarketAdService {

    @Autowired
    MarketAdMapper marketAdMapper;

    // 查询广告数据，封装入CommonData
    @Override
    public CommonData<MarketAd> list(String name, String content, BaseParam baseParam) {
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());

        MarketAdExample marketAdExample = new MarketAdExample();
        MarketAdExample.Criteria criteria = marketAdExample.createCriteria();

        // 根据需求，调用相应的方法
        if (name != null) {
            name = "%" + name.trim() + "%";
            criteria.andNameLike(name);
        }
        if (content != null) {
            content = "%" + content.trim() + "%";
            criteria.andContentLike(content);
        }

        criteria.andDeletedEqualTo(false);

        List<MarketAd> marketAds = marketAdMapper.selectByExample(marketAdExample);
        PageInfo<MarketAd> marketAdPageInfo = new PageInfo<>(marketAds);
        CommonData data = CommonData.data(marketAdPageInfo);
        return data;
    }

    // 删除广告
    @Override
    public int delete(MarketAd marketAd) {
        marketAd.setDeleted(true);
        int update = marketAdMapper.updateByPrimaryKeySelective(marketAd);
        return update;
        // int deleteByPrimaryKey = marketAdMapper.deleteByPrimaryKey(marketAd.getId());
        // return deleteByPrimaryKey;
    }

    /**
     * 返回参数与请求参数相比，多了id, addTime, updateTime(后两者初始值相同)
     * addTime, updateTime既要存入数据库，也要存入marketAd返回回去
     * @param marketAd
     * @return marketAd
     */
    @Override
    public MarketAd create(MarketAd marketAd) {
        Date date = new Date();
        marketAd.setAddTime(date);
        marketAd.setUpdateTime(date);
        int insertSelective = marketAdMapper.insertSelective(marketAd);
        return marketAd;
    }

    /**
     * 更新广告
     * 注意要修改updateTime
     * @param marketAd
     * @return marketAd
     */
    @Override
    public MarketAd update(MarketAd marketAd) {
        Date date = new Date();
        marketAd.setUpdateTime(date);
        int updateByPrimaryKey = marketAdMapper.updateByPrimaryKeySelective(marketAd);
        return marketAd;
    }
}
